package com.situ.company.employee.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;

import com.situ.company.employee.model.EmployeeModel;
import com.situ.company.employee.service.IEmployeeService;
import com.situ.company.employee.service.impl.EmployeeServiceImpl;
import com.situ.company.util.FmtEmpty;
import com.situ.company.util.FmtRequest;
import com.situ.company.util.FmtUpload;

@WebServlet("/EmployeeUploadServlet")
public class EmployeeUploadServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private IEmployeeService service = new EmployeeServiceImpl();
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Map<String, Object> map = null;
		try {
			map = FmtUpload.upload(req);
		} catch (FileUploadException | IOException e) {
			e.printStackTrace();
		}
		String code = map.get("code").toString();
		EmployeeModel model = new EmployeeModel();
		model.setCode(code);
		
		EmployeeModel mdb = service.selectModel(model);
		if(!FmtEmpty.isEmpty(mdb.getImage()))
			FmtUpload.delFile(mdb.getImage());
		
		List<String> filenames = (List<String>)map.get(FmtUpload.FILE_NAMES);
		String image = filenames.get(0);
		model.setImage(image);
		String res = service.update(model);
		Map<String, String> result = new HashMap<String, String>();
		result.put("code", res);
		result.put("image", image);
		FmtRequest.write(resp.getWriter(), result);
	}
}
